local ffi = require "ffi"
local jit = require('jit')
local pp = require('pretty-print')

--重复声明会报错，用pcall屏蔽错误
if "Windows" == jit.os then
    pcall(function ()
        ffi.cdef[[
            typedef unsigned short WORD;
            typedef struct _SYSTEMTIME {
                WORD wYear;
                WORD wMonth;
                WORD wDayOfWeek;
                WORD wDay;
                WORD wHour;
                WORD wMinute;
                WORD wSecond;
                WORD wMilliseconds;
            } SYSTEMTIME;
            void GetLocalTime(SYSTEMTIME * stUTC);
        ]]
    end)
else
    pcall(function ()
        ffi.cdef[[
            struct timezone{
                int tz_minuteswest;
                int tz_dsttime;
            };
            struct timeval {
                long tv_sec; /* seconds */
                long tv_usec; /* microseconds */
            };
            int gettimeofday(struct timeval *tv, struct timezone *tz);
        ]]
    end)
end

--获取当前时间的毫秒数
local function getCurrTime()
    if "Windows" == jit.os then
        local kernel32 = ffi.load("kernel32")
        local tm = ffi.new("SYSTEMTIME")
        kernel32.GetLocalTime(tm)
        local seconds = os.time({year=tm.wYear,month=tm.wMonth,day=tm.wDay,hour=tm.wHour,min=tm.wMinute,sec=tm.wSecond})
        local timemillis = seconds * 1000 + tm.wMilliseconds
        return timemillis
    else
        local tm = ffi.new("struct timeval")
        local tzone = ffi.new("struct timezone")
        ffi.C.gettimeofday(tm, tzone)
        local timemillis = tm.tv_sec * 1000 + tm.tv_usec/1000
        return timemillis
    end
end

local M = {}
M.new = function (ctx, initParam)
    print(initParam)
    local onlineCount = 0
    local filter = {}
    filter.match = function (req, resp, ctx)
        return true
    end
    filter.handle = function (req, resp, ctx, go)
        onlineCount = onlineCount + 1
        local count = onlineCount
        local tStart = getCurrTime()
        go()
        local tEnd = getCurrTime()
        onlineCount = onlineCount - 1
        pp.print(os.date("%Y-%m-%d %H:%M:%S") .. ", online count:" .. tostring(count) .. ", cost time:" .. tostring((tEnd - tStart)/1000) .. "s, url:" .. req.url)
    end
    return filter
end

local moduleName = ...
_G[moduleName] = M
complex = M
return complex